<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in sys_notice_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['banner:banner:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['banner:banner:remove']"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            :disabled="multiple"
            @click="handleBatchStatus(0)"
            v-hasPermi="['banner:banner:edit']"
        >批量正常</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            :disabled="multiple"
            @click="handleBatchStatus(1)"
            v-hasPermi="['banner:banner:edit']"
        >批量关闭</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['banner:banner:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bannerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="轮播图ID" align="center" prop="bannerId" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="图片" align="center" prop="imageUrl" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.imageUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="链接地址" align="center" prop="linkUrl" />
      <el-table-column label="排序" align="center" prop="sortOrder" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_notice_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['banner:banner:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['banner:banner:remove']">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column label="上线/下线" align="center" width="120">
        <template #default="scope">
          <el-switch
              :model-value="getSwitchValue(scope.row)"
              :active-value="0"
              :inactive-value="1"
              active-text="上线"
              inactive-text="下线"
              @change="(val) => handleStatusChange(scope.row, val)"
          />
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改广告管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="bannerRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="图片" prop="imageUrl">
          <image-upload v-model="form.imageUrl"/>
        </el-form-item>
        <el-form-item label="链接地址" prop="linkUrl">
          <el-input v-model="form.linkUrl" placeholder="请输入链接地址" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input v-model="form.sortOrder" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_notice_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Banner">
import {listBanner, getBanner, delBanner, addBanner, updateBanner, updateBannerStatus} from "@/api/banner/banner"
import {onMounted, nextTick } from "vue";

const { proxy } = getCurrentInstance()
const { sys_notice_status } = proxy.useDict('sys_notice_status')


// 添加一个标志位来控制是否允许状态变化
const allowStatusChange = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    status: null,
    startTime: null,
    endTime: null,
  },
  rules: {
    title: [
      { required: true, message: "标题不能为空", trigger: "blur" }
    ],
    imageUrl: [
      { required: true, message: "图片地址不能为空", trigger: "blur" }
    ],
  }
})

// 获取开关值的计算方式
const getSwitchValue = (row) => {
  return Number(row.status)
}



const bannerList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")


const { queryParams, form, rules } = toRefs(data)

/** 查询广告管理列表 */
function getList() {
  loading.value = true
  // 在数据加载前禁止状态变化
  allowStatusChange.value = false

  listBanner(queryParams.value).then(response => {
    bannerList.value = response.rows.map(item => ({
      ...item,
      status: Number(item.status),
      bannerId: Number(item.bannerId),
      sortOrder: Number(item.sortOrder)
    }))
    total.value = response.total
    loading.value = false

    // 数据加载完成后，延迟一段时间再允许状态变化
    nextTick(() => {
      setTimeout(() => {
        allowStatusChange.value = true
      }, 100)
    })
  })
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    bannerId: null,
    title: null,
    imageUrl: null,
    linkUrl: null,
    sortOrder: null,
    status: null,
    startTime: null,
    endTime: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("bannerRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.bannerId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加广告管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _bannerId = row.bannerId || ids.value
  getBanner(_bannerId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改广告管理"
  })
}

/** 批量修改状态操作 */
function handleBatchStatus(status) {
  const bannerIds = ids.value

  // 调试信息
  console.log('当前选中的ID:', bannerIds)
  console.log('选中数量:', bannerIds ? bannerIds.length : 0)

  if (!bannerIds || bannerIds.length === 0) {
    proxy.$modal.msgError("请先选择要操作的记录")
    return
  }

  const statusText = status === 0 ? "正常" : "关闭"

  proxy.$modal.confirm(`是否确认将选中的 ${bannerIds.length} 条记录状态修改为"${statusText}"？`).then(() => {
    // 构建请求数据
    const requestData = {
      bannerIds: bannerIds.map(id => Number(id)), // 确保是数字数组
      status: status.toString() // 确保是字符串
    }

    console.log('发送的请求数据:', JSON.stringify(requestData))

    return updateBannerStatus(requestData)
  }).then(() => {
    proxy.$modal.msgSuccess(`批量${statusText}成功`)
    getList();
    // 清空选择
    ids.value = []

  }).catch((error) => {
    console.error('批量操作失败:', error)
    proxy.$modal.msgError("操作失败：" + (error.message || '未知错误'))
  })
}

/** 状态切换操作 */
function handleStatusChange(row, newStatus) {
  // 如果不允许状态变化，直接返回
  if (!allowStatusChange.value) {
    console.log('状态变化被阻止：初始化期间')
    return
  }

  // 如果状态没有实际变化，直接返回
  if (Number(row.status) === Number(newStatus)) {
    console.log('状态没有变化，跳过操作')
    return
  }

  const oldStatus = row.status;
  const statusText = newStatus === 0 ? "上线" : "下线";

  proxy.$modal.confirm(`确认将"${row.title}"${statusText}?`)
      .then(() => {
        const requestData = {
          bannerIds: [Number(row.bannerId)],
          status: newStatus.toString()
        };

        return updateBannerStatus(requestData)
            .then(() => {
              proxy.$modal.msgSuccess(`${statusText}成功`);
              // 更新本地数据状态
              row.status = newStatus;
            });
      })
      .catch(() => {
        // 恢复原状态
        row.status = oldStatus;
        proxy.$modal.msgWarning(`${statusText}已取消`);
      });
}




/** 提交按钮 */
function submitForm() {
  proxy.$refs["bannerRef"].validate(valid => {
    if (valid) {
      if (form.value.bannerId != null) {
        updateBanner(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addBanner(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _bannerIds = row.bannerId || ids.value
  proxy.$modal.confirm('是否确认删除广告管理编号为"' + _bannerIds + '"的数据项？').then(function() {
    return delBanner(_bannerIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('banner/banner/export', {
    ...queryParams.value
  }, `banner_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList()
})

</script>
